package com.hiyee.utils;

import com.hiyee.utils.extend.AliyunResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.aliyun.tea.*;
import com.aliyun.dysmsapi20170525.*;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.*;
import com.aliyun.teaopenapi.models.*;

/**
 * 阿里云发送短信工具类
 *
 * @author WangBin
 */
@Component
public class SmsUtils {

    @Autowired
    AliyunResource aliyunResource;

    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    /**
     * 发送短信
     *
     * @param mobile
     * @param code
     * @return bool
     */
    public boolean sendSmsCode(String mobile, String code) {
        boolean result = false;
        try {
            com.aliyun.dysmsapi20170525.Client client = SmsUtils.createClient(aliyunResource.getAccessKeyID(), aliyunResource.getAccessKeySecret());
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(mobile)
                    .setSignName(aliyunResource.getSignName())
                    .setTemplateCode(aliyunResource.getSmsCodeTplCode())
                    .setTemplateParam("{\"code\":\"" + code + "\"}");
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse response = client.sendSms(sendSmsRequest);
            if(response.getBody().getCode().equals("OK") ) {
                result = true;
            }
            System.out.println(response.getBody().getMessage());
        } catch (Exception exception) {
            System.err.println(exception.getMessage());
        }
        return result;
    }
}
